package com.yuexin.project.system.user.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Maps;
import com.yuexin.framework.aspectj.lang.enums.DataSourceType;
import com.yuexin.framework.datasource.DynamicDataSourceContextHolder;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuexin.common.utils.StringUtils;
import com.yuexin.common.utils.ThreeDES;
import com.yuexin.common.utils.security.ShiroUtils;
import com.yuexin.framework.web.controller.BaseController;
import com.yuexin.framework.web.domain.AjaxResult;
import com.yuexin.project.abutment.domain.Company;
import com.yuexin.project.abutment.domain.UserToken;
import com.yuexin.project.abutment.mapper.AbutmentMapper;
import com.yuexin.project.order.domain.ManagerUser;
import com.yuexin.project.order.mapper.ManagerUserMapper;
import com.yuexin.project.system.user.domain.User;
import com.yuexin.project.system.user.mapper.UserMapper;
import com.yuexin.project.system.user.service.IUserService;

/**
 * 登录验证
 *
 * @author yuexin
 */
@Controller
public class LoginController extends BaseController
{
	@Autowired
	private AbutmentMapper abutmentMapper;

	@Autowired
	private IUserService userService;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private ManagerUserMapper managerUserMapper;

	private  final Logger log= LoggerFactory.getLogger(LoginController.class);

	private boolean isOrgExist(String orgId){
		boolean result = false;
		List<String>  orgIds = abutmentMapper.selectCompanyId();
		for(String id : orgIds){
			if(orgId.equals(id)){
				result = true;
				break;
			}
		}
		return result;
	}

	private User isUserIdExist(String userId){
		User userResult = new User();
		List<User> users = userMapper.selectUserAll();
		for(User user : users){
			if(userId.equals(user.getOaUserId())){
				userResult = user;
				userResult.setIsOAUserId("1");
				break;
			}
		}
		return userResult;
	}

	/**
	 * 从OA后台跳转
	 * */
	@GetMapping("/oalogin")
	@ResponseBody
    public void oalogin(@RequestParam final String token,HttpServletRequest request, HttpServletResponse response)
    {
		try {
			String tokenRequestParam = request.getParameter("token");
			String encodedParam = URLEncoder.encode(tokenRequestParam, "UTF-8");
			log.info("pc_token==="+encodedParam);
			String decodefirString = ThreeDES.decryptThreeDESECB(tokenRequestParam,"be80cb80a4f3e7225209a083e53e3ac0");
			JSONObject jobj = JSON.parseObject(decodefirString);
			String orgId = (String) jobj.get("orgId");
			String userId = (String) jobj.get("userId");

			//判断公司是否开通,如果未开通跳转到未开通提示页,已开通则根据公司账号判断是否进入试用期页面
			if(isOrgExist(orgId)){//已开通
				Company company = abutmentMapper.selectCompany(orgId);
				String companyIp = company.getCompanyIp();
				String companyPort = company.getCompanyPort();
				String status = company.getStatus();
				if("1".equals(status)) {//正常状态
					String url = "http://"+companyIp+":"+companyPort+"/meals/oaRealLogin?token="+encodedParam;
					//String url = "https://"+companyIp+"/meals/oaRealLogin?token="+encodedParam;
					response.sendRedirect(url);
				} else if("0".equals(status)) {//试用状态
					response.sendRedirect("/meals/abutment/probation?orgId="+orgId+"&companyIp="+companyIp+"&companyPort="+companyPort+"&type=oa"+"&tokenParam="+encodedParam);
				} else {//异常状态
					response.sendRedirect("/meals/abutment/errorpage");
				}
			}else {//未开通
				response.sendRedirect("/meals/abutment/notopen?orgId="+orgId+"&userId="+userId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	/**
	 * OA登录(公司服务器)
	 * */
	@GetMapping("/oaRealLogin")
	@ResponseBody
    public void oaRealLogin(@RequestParam final String token,HttpServletRequest request, HttpServletResponse response)
    {
		String tokenRequestParam = request.getParameter("token");
		try {
			String decodefirString = ThreeDES.decryptThreeDESECB(tokenRequestParam,"be80cb80a4f3e7225209a083e53e3ac0");
			JSONObject jobj = JSON.parseObject(decodefirString);
			String orgId = (String) jobj.get("orgId");
			String userId = (String) jobj.get("userId");
			String userName = (String) jobj.get("userName");
			//if(isOrgExist(orgId)){

			    //判断用户是否已关联
				User user = isUserIdExist(userId);
				//用户表存在用户标识,说明已关联
				if("1".equals(user.getIsOAUserId())){
					User oauser = userMapper.selectUserByOAUserId(userId);
					String oaloginName = oauser.getLoginName();
					String realPwd = oauser.getRealPwd();
					Integer sysuserId = oauser.getUserId().intValue();

					//判断用户是否有登录后台权限
					ManagerUser managerUser = new ManagerUser();
					managerUser.setUserId(sysuserId);
					List<ManagerUser> managerUserList = managerUserMapper.selectManagerUserList(managerUser);
					if(managerUserList == null || managerUserList.size() <= 0) {
						//return error("用户无权限进入订餐后台");
						response.sendRedirect("/meals/abutment/errorpage?status=5");
					}

					//根据公司账号判断当前公司账号是否存在用户信息
					Company comp = abutmentMapper.selectCompany(orgId);
					String compId = comp.getCompId();
					User isUser = new User();
					isUser.setCompanyId(compId);
					isUser.setLoginName(oaloginName);
					List<User> userList = userMapper.selectUserList(isUser);

					if(userList == null || userList.size() <= 0) {
						//return error("用户不存在或已被删除");
						response.sendRedirect("/meals/abutment/errorpage?status=1");
					}

					if("2".equals(oauser.getDelFlag())) {
						//return error("您的账号已被删除");
						response.sendRedirect("/meals/abutment/errorpage?status=2");
					}

					if("1".equals(oauser.getStatus())) {
						//return error("您的账号已被禁用");
						response.sendRedirect("/meals/abutment/errorpage?status=3");
					}

					//如果用户表存在用户标识，已关联账号，自动登录进入到后台主页
					//System.out.println("setStatus=====1");

					UsernamePasswordToken oaToken = new UsernamePasswordToken(oaloginName, realPwd, "");
			        Subject subject = SecurityUtils.getSubject();
			        subject.login(oaToken);
			        SecurityUtils.getSubject().getSession().setTimeout(-1000l);//设置session不过期
			        //设置当前用户的公司ID
			        String companyId = oauser.getCompanyId();
			        ShiroUtils.setCompanyId(companyId);
			        response.sendRedirect("/meals/index");
				}else{
					//如果用户表不存在用户标识，进入到账号注册设置页面
					//System.out.println("setStatus=====2");
					userName = URLEncoder.encode(userName,"UTF-8");
					response.sendRedirect("/meals/abutment/setaccount?userName="+userName+"&orgId="+orgId+"&userId="+userId );
				}
			/*}else{
				System.out.println("setStatus=====3");
				response.sendRedirect("/meals/abutment/notopen?orgId="+orgId+"&userId="+userId);
			}*/

		} catch (Exception e1) {
			log.error("", e1);
			try {
				response.sendRedirect("/meals/abutment/errorpage");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }

	/**
	 * 手机端首页登录（登录服务器）
	 * */
	@PostMapping("/firstLoginMobile")
	@ResponseBody
    public AjaxResult firstLoginMobile(String companyAccount,String loginName,String loginPwd)
    {
		Company comp = abutmentMapper.selectCompanyByAccount(companyAccount);
		if(comp == null ) {
			return error("公司账号不存在");
		}else {
			return success(comp);
		}
    }

	/**
	 * 手机端首页登录（公司服务器）
	 * */
	@PostMapping("/firstLoginMobileSaaS")
	@ResponseBody
    public AjaxResult firstLoginMobileSaaS(String companyAccount,String loginName,String loginPwd)
    {
		Company comp = abutmentMapper.selectCompanyByAccount(companyAccount);
		String compId = comp.getCompId();
		User isUser = new User();
		isUser.setCompanyId(compId);
		isUser.setLoginName(loginName);
		List<User> userList = userMapper.selectUserList(isUser);
		if(userList == null || userList.size() <= 0) {
			return error("用户不存在");
		}

		UsernamePasswordToken oaToken = new UsernamePasswordToken(loginName, loginPwd, "");
        Subject subject = SecurityUtils.getSubject();
        subject.login(oaToken);
//        User oauser = userMapper.selectUserByLoginName(loginName);
//        String companyId = oauser.getCompanyId();
//        ShiroUtils.setCompanyId(companyId);
        return success();
    }

	@PostMapping("/firstLogin")
	@ResponseBody
    public AjaxResult firstLogin(String companyAccount) {
		DynamicDataSourceContextHolder.setDateSoureType(DataSourceType.SLAVE.name());
    	Company comp = abutmentMapper.selectCompanyByAccount(companyAccount);
		Map<String,String> map = Maps.newHashMap();
		if(comp == null ) {
			return error("公司账号不存在");
		}else {
			String orgId = comp.getOrgId();
			String companyIp = comp.getCompanyIp();
			String companyPort = comp.getCompanyPort();
			String status = comp.getStatus();
			map.put("orgId", orgId);
			map.put("companyAccount", companyAccount);
			map.put("companyIp", companyIp);
			map.put("companyPort", companyPort);
			map.put("status", status);
			DynamicDataSourceContextHolder.clearDateSoureType();
			DynamicDataSourceContextHolder.setDateSoureType(DataSourceType.MASTER.name());
			return success(map);
		}
    }

	@GetMapping("/firstRealLogin")
	@ResponseBody
    public AjaxResult firstRealLogin(String loginName,String loginPwd,String orgId,String companyAccount,HttpServletRequest request, HttpServletResponse response)
    {
		try {
			//判断用户是否有登录后台权限
			User user = userMapper.selectUserByLoginName(loginName);
			if(user !=null) {
				ManagerUser managerUser = new ManagerUser();
				Integer sysuserId = user.getUserId().intValue();
				managerUser.setUserId(sysuserId);
				List<ManagerUser> managerUserList = managerUserMapper.selectManagerUserList(managerUser);
				if(managerUserList == null || managerUserList.size() <= 0) {
					//return error("用户无权限进入订餐后台");
					response.sendRedirect("/meals/abutment/errorpage?status=5");
				}
			}
			//根据公司账号判断当前公司账号是否存在用户信息
			Company comp = abutmentMapper.selectCompanyByAccount(companyAccount);
			String compId = comp.getCompId();
			User isUser = new User();
			isUser.setCompanyId(compId);
			isUser.setLoginName(loginName);
			List<User> userList = userMapper.selectUserList(isUser);

			if(userList == null || userList.size() <= 0) {
				//return error("用户不存在或已被删除");
				response.sendRedirect("/meals/abutment/errorpage?status=1");
			}

			if("2".equals(user.getDelFlag())) {
				//return error("您的账号已被删除");
				response.sendRedirect("/meals/abutment/errorpage?status=2");
			}

			if("1".equals(user.getStatus())) {
				//return error("您的账号已被禁用");
				response.sendRedirect("/meals/abutment/errorpage?status=3");
			}

			UsernamePasswordToken oaToken = new UsernamePasswordToken(loginName, loginPwd, "");
	        Subject subject = SecurityUtils.getSubject();
	        subject.login(oaToken);
	        SecurityUtils.getSubject().getSession().setTimeout(-1000l);//设置session不过期
	        User oauser = userMapper.selectUserByLoginName(loginName);
	        String companyId = oauser.getCompanyId();
	        //System.out.println("companyId==========="+companyId);
	        ShiroUtils.setCompanyId(companyId);
	        response.sendRedirect("/meals/index");
		} catch (Exception e) {
			try {
				log.error("登录有误:", e);
				response.sendRedirect("/meals/abutment/errorpage?status=4");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
        return success();
    }

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response)
    {
        // 如果是Ajax请求，返回Json字符串。
    	return "login";
    }

    /**
     * OA手机端点击进入时(登录服务器)
     * 判断公司开通状态 1开通 0其他未开通
     * */
    @PostMapping("/oaMobileLogin")
    @ResponseBody
    public AjaxResult oaMobileLogin(String oaToken)
    {
		try {
	        log.info("mobile_token==="+oaToken);
			String decodedParam = URLDecoder.decode(oaToken, "UTF-8");
			String decodefirString = ThreeDES.decryptThreeDESECB(decodedParam,"be80cb80a4f3e7225209a083e53e3ac0");
			JSONObject jobj = JSON.parseObject(decodefirString);
			String orgId = (String) jobj.get("orgId");
			String userId = (String) jobj.get("userId");
			String userName = (String) jobj.get("userName");
			UserToken userToken = new UserToken();
			userToken.setOrgId(orgId);
			userToken.setUserId(userId);
			userToken.setUserName(userName);

			//判断公司是否存在开通，如果公司表存在公司标识则为已开通
			if(isOrgExist(orgId)){
				//开通
				userToken.setStatus("1");
				return success(userToken);
			}else{
				//未开通
				userToken.setStatus("0");
				return success(userToken);
			}
		} catch (Exception e) {
			return error();
		}
    }

    /**
     * OA手机端点击进入时(公司服务器)
     * 判断用户是否关联 1关联 0其他未关联
     * */
    @PostMapping("/oaMobileLoginSaaS")
    @ResponseBody
    public AjaxResult oaMobileLoginSaaS(String oaUserId)
    {
    	User user = isUserIdExist(oaUserId);
    	UserToken userToken = new UserToken();
		userToken.setUserId(oaUserId);

		//根据公司账号判断当前公司账号是否存在用户信息
    	if("1".equals(user.getIsOAUserId())){
			//如果用户表存在用户标识，已关联账号，自动登录进入到手机订餐页面

    		User oauser = userMapper.selectUserByOAUserId(oaUserId);
    		if("2".equals(oauser.getDelFlag())) {
    			userToken.setStatus("3");
    		}

    		if("1".equals(oauser.getStatus())) {
    			userToken.setStatus("4");
    		}
    		if("0".equals(oauser.getDelFlag()) && "0".equals(oauser.getStatus())) {
    			userToken.setStatus("1");
    		}
			return success(userToken);
		}else{
			//如果用户表不存在用户标识，进入到账号注册设置页面
			userToken.setStatus("0");
			return success(userToken);
		}
    }

    /**
     * OA手机端获取token 根据oaUserId
     *
     * */
    @PostMapping("/oamobiletoken")
    @ResponseBody
    public AjaxResult oaMobileToken(String oaUserId)
    {
    	User user = userMapper.selectUserByOAUserId(oaUserId);
    	return success(user);

    }

    /**
     * OA手机端获取token  根据loginName
     *
     * */
    @PostMapping("/oamobiletokenByLoginName")
    @ResponseBody
    public AjaxResult oamobiletokenByLoginName(String loginName)
    {
    	User user = userMapper.selectUserByLoginName(loginName);
    	return success(user);
    }

    /**
     * OA手机端登录绑定(登录服务器)
     *
     * */
    @PostMapping("/oamobileloginbind")
	@ResponseBody
	 public AjaxResult oaMobileLoginBind(String companyAccount,String userName,String password,String oaUserId,String oaOrgId)
    {
		Company comp = abutmentMapper.selectCompanyByAccount(companyAccount);
		Map<String,Object> map = new HashMap<String,Object>();
        map.put("company", comp);

        //超级管理员来设置更新插入公司标识
        comp.setOrgId(oaOrgId);
        abutmentMapper.updateCompany(comp);
        return success(map);
    }

    /**
     * OA手机端登录绑定(公司服务器)
     *
     * */
    @GetMapping("/oamobileloginbindReal")
   	@ResponseBody
   public AjaxResult oamobileloginbindReal(String companyAccount,String userName,String password,String oaUserId,String oaOrgId)
   {
    	UsernamePasswordToken oaToken = new UsernamePasswordToken(userName, password, "");
       Subject subject = SecurityUtils.getSubject();
       try
       {
	       subject.login(oaToken);

	       //登录成功后更新用户信息
	       User user = userMapper.selectUserByUserName(userName);
	       user.setOaUserId(oaUserId);
	       user.setOaOrgId(oaOrgId);
	       userMapper.updateUser(user);

	       String companyId = user.getCompanyId();
	       ShiroUtils.setCompanyId(companyId);

	       //超级管理员来设置更新插入公司标识
	       /*Company comp = abutmentMapper.selectCompanyByAccount(companyAccount);
	       comp.setOrgId(oaOrgId);
	       abutmentMapper.updateCompany(comp);*/
	       return success();
       }
       catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
   }


    /**
     * OA手机端登录绑定
     *
     * */
   /* @PostMapping("/oamobileloginbind")
    @ResponseBody
    public AjaxResult oaMobileLoginBind(String companyAccount,String userName,String password,String oaUserId,String oaOrgId)
    {
    	UsernamePasswordToken token = new UsernamePasswordToken(userName, password, "");
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);

            //登录成功后更新用户信息
            User user = userMapper.selectUserByUserName(userName);
            user.setOaUserId(oaUserId);
            user.setOaOrgId(oaOrgId);
            userMapper.updateUser(user);

            //超级管理员来设置插入公司标识
            Company company = new Company();
            company.setOrgId(oaOrgId);
            abutmentMapper.insertCompany(company);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }*/

    @PostMapping("/oaPCBind")
	@ResponseBody
    public AjaxResult oaPCBind(String oaOrgId,String oaUserId,String companyAccount,String loginName,String loginPwd)
    {
		Company comp = abutmentMapper.selectCompanyByAccount(companyAccount);
		if(comp == null ) {
			return error("公司账号不存在");
		}else {
			String companyIp = comp.getCompanyIp();
			String companyPort = comp.getCompanyPort();

			//超级管理员来设置更新插入公司标识
	        comp.setOrgId(oaOrgId);
	        abutmentMapper.updateCompany(comp);

			Map<String,String> map = new HashMap<String,String>();
	        String bindURL = "http://"+companyIp+":"+companyPort+"/meals/oaPCBindLogin?loginName="+loginName+"&loginPwd="+loginPwd+"&orgId="+oaOrgId+"&oaUserId="+oaUserId+"&companyAccount="+companyAccount;
	        //String bindURL = "https://"+companyIp+"/meals/oaPCBindLogin?loginName="+loginName+"&loginPwd="+loginPwd+"&orgId="+oaOrgId+"&oaUserId="+oaUserId+"&companyAccount="+companyAccount;
	        map.put("bindURL", bindURL);
	        return success(map);
		}
    }

    @GetMapping("/oaPCBindLogin")
	@ResponseBody
    public void oaPCBindLogin(@RequestParam final String loginName,@RequestParam final String loginPwd,@RequestParam final String orgId,@RequestParam final String oaUserId,@RequestParam final String companyAccount,HttpServletRequest request, HttpServletResponse response)
    {
		String loginNameParam = request.getParameter("loginName");
		String loginPwdParam = request.getParameter("loginPwd");
		//String orgIdParam = request.getParameter("orgId");
		String userIdParam = request.getParameter("oaUserId");
		//String companyAccountParam = request.getParameter("companyAccount");
		UsernamePasswordToken oaToken = new UsernamePasswordToken(loginNameParam, loginPwdParam, "");
        Subject subject = SecurityUtils.getSubject();
        subject.login(oaToken);
        SecurityUtils.getSubject().getSession().setTimeout(-1000l);//设置session不过期

        //登录成功后更新用户信息
        User user = userMapper.selectUserByUserName(loginName);
        user.setOaUserId(userIdParam);
        user.setOaOrgId(orgId);
        userMapper.updateUser(user);
        String companyId = user.getCompanyId();
        ShiroUtils.setCompanyId(companyId);

        try {
        	response.sendRedirect("/meals/index");
        }catch (Exception e1) {
			e1.printStackTrace();
		}

        /* Company comp = abutmentMapper.selectCompanyByAccount(companyAccountParam);
        //超级管理员来设置更新插入公司标识
        comp.setOrgId(orgId);
        abutmentMapper.updateCompany(comp);*/

		/*String companyStatus = comp.getStatus();
		try {
			if("0".equals(companyStatus)) {
				response.sendRedirect("/meals/abutment/probation?orgId="+orgId);
			}else if("1".equals(companyStatus)) {
				response.sendRedirect("/meals/index");
			}else {
				response.sendRedirect("/meals/abutment/errorpage");
			}
		}catch (Exception e1) {
			e1.printStackTrace();
		}*/
    }

    /**
     * OA登录绑定
     *
     * */
    /*@PostMapping("/oaPCBind")
    @ResponseBody
    public AjaxResult oaPCBind(String orgId,String oaUserId,String loginName,String loginPwd)
    {
    	UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPwd, "");
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            ShiroUtils.setCompanyId(orgId);

            //登录成功后更新用户信息
            User user = userMapper.selectUserByUserName(loginName);
            user.setOaUserId(oaUserId);
            user.setOaOrgId(orgId);
            userMapper.updateUser(user);

            //超级管理员来设置插入公司标识
            Company company = new Company();
            company.setOrgId(orgId);
            abutmentMapper.insertCompany(company);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }*/

    /**
     * OA电脑端设置账号页面登录绑定
     *
     * */
    @PostMapping("/oaAccountPCBind")
    @ResponseBody
    public AjaxResult oaAccountPCBind(String orgId,String oaUserId,String userName,String loginName,String loginPwd)
    {
    	UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPwd, "");
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            SecurityUtils.getSubject().getSession().setTimeout(-1000l);//设置session不过期

            //登录成功后更新用户信息
            User user = userMapper.selectUserByUserName(loginName);
            Company comp = abutmentMapper.selectCompany(orgId);
            String compId = comp.getCompId();
            user.setUserName(userName);
            user.setOaUserId(oaUserId);
            user.setOaOrgId(orgId);
            user.setCompanyId(compId);
            user.setRealPwd(loginPwd);
            userMapper.updateUser(user);

            String companyId = user.getCompanyId();
            ShiroUtils.setCompanyId(companyId);

            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    /**
     * OA手机端设置注册
     *
     * */
    @PostMapping("/oamobileregister")
    @ResponseBody
    public AjaxResult oaMobileRegister(String loginName,String password,String userName,String orgId,String oaUserId,String companyId)
    {
    	User user = new User();
    	user.setLoginName(loginName);
    	user.setPassword(password);
    	user.setUserName(userName);
    	user.setOaOrgId(orgId);
    	user.setOaUserId(oaUserId);
    	user.setCompanyId(companyId);
    	int count = userMapper.checkLoginNameUnique(loginName);
    	if (count > 0)
        {
            return error(-1,"用户名已存在！");
        }
    	if(user.getDeptId() == null) {
         	user.setDeptId((long) 100);
        }
    	userService.insertMobileUser(user);
    	return success();
    }

    /**
     * OA电脑端设置注册
     *
     * */
    @PostMapping("/oaPCRegister")
    @ResponseBody
    public AjaxResult oaPCRegister(String userName,String orgId,String oaUserId,String loginName,String password)
    {
    	User user = new User();
    	Company comp = abutmentMapper.selectCompany(orgId);
    	String companyId = comp.getCompId();
    	user.setLoginName(loginName);
    	user.setPassword(password);
    	user.setUserName(userName);
    	user.setOaOrgId(orgId);
    	user.setOaUserId(oaUserId);
    	user.setRealPwd(password);
    	user.setCompanyId(companyId);
    	int count = userMapper.checkLoginNameUnique(loginName);
    	if (count > 0)
        {
            return error(-1,"用户名已存在！");
        }
    	if(user.getDeptId() == null) {
         	user.setDeptId((long) 100);
        }
    	userService.insertMobileUser(user);

    	UsernamePasswordToken token = new UsernamePasswordToken(loginName, password, "");
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        ShiroUtils.setCompanyId(companyId);
    	return success();
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe,String isMobile)
    {
    	//移动端请求处理
    	//isMobile = "1";
    	if("1".equals(isMobile)){
    		System.out.println("移动端登录。。。。。");
    		Map<String,Object> mapToken = new HashMap<String,Object>();
    		mapToken.put("tokenId", "999999999");
    		mapToken.put("userName", username);
    		mapToken.put("password", password);
    		Date dt = new Date();
    	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		mapToken.put("createTime", sdf.format(dt));

    		//仍然执行登录动作,后期要改
    		UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
	        Subject subject = SecurityUtils.getSubject();
	        try
	        {
	            subject.login(token);
	            return successForMobile(mapToken);
	        }
	        catch (AuthenticationException e)
	        {
	            String msg = "用户或密码错误";
	            if (StringUtils.isNotEmpty(e.getMessage()))
	            {
	                msg = e.getMessage();
	            }
	            return error(msg);
	        }

    	}else{
    		System.out.println("电脑端登录。。。。。");
    		UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
	        Subject subject = SecurityUtils.getSubject();
	        try
	        {
	            subject.login(token);
	            SecurityUtils.getSubject().getSession().setTimeout(-1000l);//设置session不过期
	            return success();
	        }
	        catch (AuthenticationException e)
	        {
	            String msg = "用户或密码错误";
	            if (StringUtils.isNotEmpty(e.getMessage()))
	            {
	                msg = e.getMessage();
	            }
	            return error(msg);
	        }
    	}
    }

    @GetMapping("/unauth")
    public String unauth()
    {
        return "/error/unauth";
    }

	/**
	 * 生成密码
	 */
	@GetMapping("/generatePwd")
	@ResponseBody
	public AjaxResult generatePassword(@Param("userName") String userName, @Param("pwd") String pwd) {
		User user = new User();
		user.setLoginName(userName);
		user.setPassword(pwd);
		return AjaxResult.success(userService.generatePassword(user));
	}
}
